package com.zxp.utils.fileUtils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) {
        String directoryPath = "path/to/your/directory";
        String filePath = "path/to/your/file.txt";
        String content = "Hello, World!";

        if (FileUtils.createDirectory(directoryPath)) {
            System.out.println("Directory created successfully.");
        } else {
            System.err.println("Failed to create directory.");
        }

        if (FileUtils.createFile(filePath)) {
            System.out.println("File created successfully.");
        } else {
            System.err.println("Failed to create file.");
        }

        if (FileUtils.writeToFile(filePath, content)) {
            System.out.println("Content written to file successfully.");
        } else {
            System.err.println("Failed to write content to file.");
        }
    }

    /**
     * Create a directory.
     * @param directoryPath The path of the directory.
     * @return true if the directory is created successfully or already exists, false if creation fails.
     */
    public static boolean createDirectory(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            return directory.mkdirs();
        }
        return true;
    }

    /**
     * Create a file.
     * @param filePath The path of the file.
     * @return true if the file is created successfully or already exists, false if creation fails.
     */
    public static boolean createFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * Write content to a file.
     * @param filePath The path of the file.
     * @param content The content to be written to the file.
     * @return true if writing is successful, false if writing fails.
     */
    public static boolean writeToFile(String filePath, String content) {
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(content);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    public static String readJsonFile(String filePath) throws IOException {
        File jsonFile = new File(filePath);

        if (jsonFile.exists()) {
            JsonNode rootNode = objectMapper.readTree(jsonFile);
            return rootNode.toString();
        } else {
            return "File not found: " + filePath;
        }
    }
}
